package com.boomsecret.juc.tools;

import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;

/**
 * @author wangjinliang on 2019/1/23.
 */
public class PhaserCyclicBarrierDemo {
    private static final int THREAD_COUNT = 5;

    public static void main(String[] args) {
        Phaser phaser = new Phaser(5);
        Thread[] threads = new Thread[THREAD_COUNT];
        for (int index = 0; index < THREAD_COUNT; index ++) {
            threads[index] = new Thread(new CustomRunnable(phaser));
            threads[index].start();
        }

        for (Thread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("main end.");
    }

    public static class CustomRunnable implements Runnable {
        private Phaser phaser;

        public CustomRunnable(Phaser phaser) {
            this.phaser = phaser;
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + " start");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            this.phaser.arriveAndAwaitAdvance();
            System.out.println(Thread.currentThread().getName() + " end");
        }
    }
}